package com.example.littlepainter.data

import android.app.Application
import android.graphics.Bitmap
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.littlepainter.R
import com.example.littlepainter.db.Picture
import com.example.littlepainter.utils.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PictureViewModel(application: Application): AndroidViewModel(application) {
    private val repository = Repository()
    var models = repository.loadDatas()  //models  -> LiveData()  <-   loadDatas()

    fun savePicture(picture: Picture){
        viewModelScope.launch(Dispatchers.IO) {
            repository.addPicture(picture)
        }
    }

    fun updatePicture(picture: Picture){
        viewModelScope.launch(Dispatchers.IO) {
            repository.updatePicture(picture)
        }
    }

    fun deletePicture(index:Int){
        if (index < 0 || index >= models.value!!.size) return

        viewModelScope.launch(Dispatchers.IO) {
            val picture = models.value!![index]
            repository.deletePicture(picture)
            FileUtils().deleteFile(picture.url)
        }
    }

    fun fakeData(){
       /* val bm = Bitmap.createBitmap(10,10,Bitmap.Config.ARGB_8888)
        val datas = listOf(
            Picture(0,"","", R.drawable.f1, bm),
            Picture(0,"","", R.drawable.f2, bm),
            Picture(0,"","", R.drawable.f3, bm),
            Picture(0,"","", R.drawable.f4, bm),
            Picture(0,"","", R.drawable.f1, bm),
            Picture(0,"","", R.drawable.f2, bm),
            Picture(0,"","", R.drawable.f3, bm),
            Picture(0,"","", R.drawable.f4, bm),
            Picture(0,"","", R.drawable.f1, bm),
            Picture(0,"","", R.drawable.f2, bm),
            Picture(0,"","", R.drawable.f3, bm),
            Picture(0,"","", R.drawable.f4, bm),
        )

        models.postValue(datas)*/
    }
}